<template>
  <!-- 附件信息 -->
  <div class="m-attch-wrapper">
       <lessoUploader
          :baseUrl="baseUrl"
          :userInfo="userInfo"
          :deleteBtn="true"
          @fileError="fileError"
          @overSize="overSizeHandler"
          @fileAdded="fileAdded"
          @fileSuccess="fileSuccess"
          @invalidFileType="onInvalidFile"
          @fileProgress="fileProgress"
          @fileExceed="fileExceed"

          :limits="uploadMaxCount"
          :multiple="true"
          :showFileList="false"
          v-show="fileList.length < uploadMaxCount && isShowUploader" class="attach-btn"
          :allowDuplicateUploads="false"
        >
          <div slot="upload-btn">
            <div class="slot_btn">选择附件</div>
          </div>
        </lessoUploader>
    <ul class="file-list">
      <li
        v-for="(file, index) in fileList"
        :key="index"
        :class="{ 'file-item': true, 'progress-bar': true }"
        v-loading="file.loading && file.progress === 0"
        element-loading-background="rgba(0, 0, 0, 0.2)"
        @click="downLoadFile(file)"
      >
        <span
          class="upload-progress"
          :style="{ width: file.progress + '%' }"
          v-if="file.progress < 100"
        ></span>
        <span class="m-icon-link">
          <i class="iconfont icon-annex"></i>
          <span class="m-file-name">{{ file.name }}</span>
          <span class="color-grey">({{ getFileSize(file.length) }})</span>
        </span>
        <i class="iconfont icon-delete close" @click="deleteFile(index, $event)"></i>
        <span
          v-if="file.progress < 100"
          :style="{ width: file.progress + '%' }"
          class="upload-progress-text"
          >{{ file.progress }}%</span
        >
      </li>
    </ul>
  </div>
</template>
<style lang='less'>
.m-attch-wrapper {
  .file-list {
    li {
      position: relative;
      height: 40px;
      line-height: 40px;
      padding: 0 20px 0 0;
      margin: 10px 0;
      background: #f5f7fa;
      border: 2px solid #edeff2;
      cursor: pointer;
      transition: all 0.2s linear;
      .m-icon-link {
        position: absolute;
        left: 20px;
        top: 0;
        z-index: 10;
        display: flex;
        align-items: center;
        .icon-annex {
          margin-right: 10px;
        }
      }
      .m-file-name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 300px;
        margin-right: 5px;
      }
      .close {
        position: absolute;
        right: 20px;
        top: 50%;
        transform: translateY(-50%);
        color: #999 !important;
      }
     
      &:hover {
        color: #3071f2;
        border-color: #3071f2;
        .color-grey {
          color: #3071f2;
        }
      }
    }
  }
  .upload-progress {
    position: absolute;
    left: 0;
    top: 0;
    background: #29cc7a;
    display: block;
    content: "";
    height: 100%;
    transition: all 0.5s;
  }
  .upload-progress-text {
    position: absolute;
    z-index: 100;
    color: #fff;
    text-align: center;
    transition: all 0.5s;
  }
  .upload-tips {
    display: inline-block;
    width: 60px;
    background: #fff;
  }
  .file-item {
    align-items: center;
    justify-content: space-between;
    svg.close {
      width: 16px;
      height: 16px;
      cursor: pointer;
      color: #ccc;
    }
  }
  .attach-btn {
    .el-upload {
      display: block;
    }
    .add-btn {
      cursor: pointer;
      text-align: center;
      font-size: 13px;
    }
  }
  .uploader-list {
    display: none;
  }
}
</style>

<script>
import lessoUploader from "lesso-file-upload/lessoUploader";
import _utils from "@/public/utils";
import apienv from "@/api/env";
import constant from "@/public/constant";
import downLoadFileFunc from "@/public/downLoadFile"


export default {
  name: "VAttach",
  data() {
    return {
      fileList: [],
      baseUrl: apienv[constant.appenv].srm + "uploadFastdfs/",
      userInfo: {
        userName: this.$global.user.employeeName,
        userId: this.$global.user.id,
        groupName: "SRM"
      },
      isPass: true,
      uploadTimeout: 30000 //上传超时时间 30秒
    };
  },
  props: {
    isDownloadFile: {
      type: Boolean,
      default: true,
    },
    isShowUploader: {
      type: Boolean,
      default: true,
    },
    maxSize: {
      type: Number,
      default: 209715200
    },
    acceptFile: String,
    uploadMaxCount: {
      type: Number,
      default: Infinity
    },
    value: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  components: {
    lessoUploader
  },
  methods: {
    // 下载文件
    downLoadFile (params) {
      if(!params.viewPath || !this.isDownloadFile) return;
      var obj = {
        viewPath: params.viewPath,
        fileName: params.name,
      };
      obj.groupName = 'TEST';
      obj.fileName = ''
      if (params.viewPath.indexOf('SRM') > -1) {
        obj.groupName = 'SRM'
      } else if (params.viewPath.indexOf('SIGN') > -1) {
        obj.groupName = 'SIGN'
      } else if (params.viewPath.indexOf('TEST') > -1) {
        obj.groupName = 'TEST'
      }
      downLoadFileFunc(obj, params.name)
    },
    fileError(file, message, chunk) {
      const result = this.findInFiles(file);
      if(result.file) {
            this.fileList[result.index].file.cancel();
          this.fileList.splice(result.index, 1);
          result.file.loading = false;
      }
      message = JSON.parse(message);
      this.$message.error(message.msg);
    },
    getFileSize(fileSize) {
      return _utils.getFileSize(fileSize);
    },
    overSizeHandler() {
      this.$message.warning(
        `选择的文件大小不能超过${(this.maxSize / 1024 / 1024).toFixed(1)}M`
      );
    },
    //文件个数超出限制
    fileExceed(files, fileList) {
        for(let file of fileList) {
            file.fileExceed = true;
        }
        this.$message.warning(`上传文件个数超出限制,最多只能上传${this.uploadMaxCount}个文件`);
    },
    fileAdded(file, files) {
        console.log("fileAdded")
        if(file.fileExceed || this.fileList.length >= this.uploadMaxCount) {
            file.cancel();
            return;
        }
      this.fileList.push({
        length: file.size,
        name: file.name,
        progress: 0,
        md5: file.md5,
        loading: true,
        file
      });
    },
    fileSuccess(file, res) {
      console.log("fileSuccess")
      const { data } = res;
      const result = this.findInFiles(file);
      if (result.file) {
        result.file.viewPath = data.viewPath;
        result.file.loading = false;
      }
      this.$emit("update:value", this.fileList);
    },
    deleteFile(index, ev) {
      ev.stopPropagation();
      this.fileList[index].loading = false;
      this.fileList[index].file && this.fileList[index].file.cancel();
      this.fileList.splice(index, 1);
      this.$emit("update:value", this.fileList);
    },
    onInvalidFile() {
      this.$message.error(`只能上传${this.acceptFile}类型文件`);
    },
    fileProgress(file, progress, speed, time) {
      console.log("fileProgress")
      const result = this.findInFiles(file);
      result.file && (result.file.progress = parseInt(progress * 100));
    },
    findInFiles(file) {
      const res = {
        file: null,
        index: -1
      };
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].md5 == file.md5) {
          res.file = this.fileList[i];
          res.index = i;
          break;
        }
      }
      return res;
    }
  },
  mounted() {
    //获取文件服务地址和用户信息
    this.value.forEach(({ length, viewPath, name, md5 }) => {
      this.fileList.push({
        viewPath,
        name,
        md5,
        length
      });
    });
  }
};
</script>